import { User } from "@entity/user";
import { getMe } from "./functions";

export function myId(state: any): number {
	let me: User = getMe(state);
	return me != undefined ? me.id : -1;
}

/**
 * 本地缓存字段
 */
 export const FIELD = {
    ME					: () 			=> `olah-me`,
    PROJECT_MAP			: (id: number) 	=> `olah-${id}-project-map`,
    USER_MAP			: (id: number) 	=> `olah-${id}-user-map`,
	USER_MESSAGE_MAP	: (id: number) 	=> `olah-${id}-user-message-map`,
	SYSTEM_MESSAGE_MAP	: (id: number) 	=> `olah-${id}-system-message-map`,
	FRIEND_MAP			: (id: number)  => `olah-${id}-friend-map`,
}

/**
 * 查看指定数据是否已经过期
 */
export function isTimeout(data: any): Boolean {
	return !(data.time == -1 || Date.now() < data.time);
}

/**
 * 获取常规本地缓存
 */
export function getCache(field: string): any {
	let json: string = localStorage.getItem(field);
	let result: any = undefined;
	if (json != null) {
		let obj: any = JSON.parse(json);
		if (!isTimeout(obj)) {
			return obj.data;
		}
		delCache(field);
	}
	return result;
}

/**
 * 获取本地 map 缓存
 */
export function getMapCache(field: string): Map<any, any> {
	let json: string = localStorage.getItem(field);
	let cache: Map<any, any> = json == null ? null : Map.prototype.toMap(JSON.parse(json));
	return (cache == null || cache.size == undefined) ? new Map<number, any>() : cache;
}

/**
 * 设置本地常规缓存
 * @param time 有效期，单位分钟
 */
export function setCache(field: string, value: any, time: number = -1): void {
	localStorage.setItem(field, JSON.stringify({
		time: time == -1 ? -1 : Date.now() + (time * 60 * 1000),
		data: value
	}));
}

/**
 * 设置本地 map 缓存
 */
export function setMapCache(field: string, value: Map<any, any>): void {
	localStorage.setItem(field, JSON.stringify(value.toObj()));
}

/**
 * 删除一个本地缓存
 */
export function delCache(field: string): void {
    localStorage.removeItem(field);
}